<template>
  <div class="volunteer-comments">
    <!-- 评论统计 -->
    <el-card class="stats-card" v-loading="loading.stats">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.commentCount || 0 }}</div>
            <div class="stat-label">发表评论</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.likeCount || 0 }}</div>
            <div class="stat-label">获得点赞</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.featuredCount || 0 }}</div>
            <div class="stat-label">精选评论</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 评论列表 -->
    <el-card class="comments-card" v-loading="loading.list">
      <template #header>
        <div class="card-header">
          <el-radio-group v-model="activeTab" size="large" @change="handleTabChange">
            <el-radio-button label="all">全部评论</el-radio-button>
            <el-radio-button label="activity">活动评论</el-radio-button>
            <el-radio-button label="article">文章评论</el-radio-button>
            <el-radio-button label="course">课程评论</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-empty v-if="comments.length === 0" description="暂无评论数据" />

      <div v-else class="comments-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <div class="target-info">
              <el-tag size="small" :type="comment.type === 'activity' ? 'success' : comment.type === 'course' ? 'warning' : 'info'">
                {{ comment.type === 'activity' ? '活动' : comment.type === 'course' ? '课程' : '文章' }}
              </el-tag>
              <span class="target-title">{{ comment.targetTitle }}</span>
            </div>
            <div class="comment-time">{{ comment.time }}</div>
          </div>

          <div class="comment-author">
            <el-avatar :src="comment.avatar || 'https://placeholder.com/150'" size="small"></el-avatar>
            <span class="author-name">{{ comment.username }}</span>
          </div>

          <div class="comment-content">
            {{ comment.content }}
          </div>

          <div class="comment-footer">
            <div class="interactions">
              <span 
                class="interaction-item" 
                :class="{ 'active': comment.liked }"
                @click="handleLike(comment)">
                <el-icon><Star /></el-icon>
                {{ comment.likes }}
              </span>
              <span 
                class="interaction-item"
                @click="toggleReplies(comment)"
                v-if="comment.replies > 0">
                <el-icon><ChatDotRound /></el-icon>
                {{ comment.replies }}
              </span>
            </div>
            <div class="actions">
              <el-button text type="primary" size="small" @click="viewDetail(comment)">
                查看详情
              </el-button>
              <el-button text type="danger" size="small" @click="handleDelete(comment)">
                删除
              </el-button>
            </div>
          </div>

          <!-- 回复列表 -->
          <div v-if="comment.showReplies" class="replies-list" v-loading="comment.loadingReplies">
            <el-empty v-if="!comment.replyList || comment.replyList.length === 0" description="暂无回复" />
            <div v-else v-for="reply in comment.replyList" :key="reply.id" class="reply-item">
              <div class="reply-content">
                <span class="replier">{{ reply.username }}</span>：{{ reply.content }}
              </div>
              <div class="reply-time">{{ reply.time }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          background
          layout="prev, pager, next"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { Star, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getVolunteerComments, 
  deleteComment, 
  toggleLike 
} from '@/api/volunteer-dashboard'

const router = useRouter()
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref({
  stats: false,
  list: false
})

// 评论统计
const stats = ref({
  commentCount: 0,
  likeCount: 0,
  featuredCount: 0
})

// 原始评论列表
const rawComments = ref([])

// 处理后的评论列表
const comments = computed(() => {
  // 将原始评论转换为前端期望的格式
  return rawComments.value.map(comment => {
    // 确定评论类型
    let type = 'article';
    if (comment.targetType === 3) {
      type = 'course'; // 课程评论
    } else if (comment.targetType === 2) {
      type = 'article'; // 文章评论
    } else if (comment.targetType === 1) {
      type = 'activity'; // 活动评论
    }
    
    // 转换时间格式
    const time = comment.createTime ? new Date(comment.createTime).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }) : (comment.time || '未知时间');
    
    return {
      id: comment.id,
      userId: comment.userId,
      type,
      targetId: comment.targetId,
      targetType: comment.targetType,
      targetTitle: getTargetTitle(comment),
      content: comment.content || '',
      time,
      likes: comment.likeCount || 0,
      replies: comment.replyCount || 0,
      liked: comment.isLiked === true,
      showReplies: false,
      loadingReplies: false,
      replyList: [], // 暂时为空，需要时再获取
      avatar: comment.userAvatar || comment.avatar || 'https://placeholder.com/150',
      username: comment.userName || comment.username || '未知用户'
    };
  });
})

// 获取目标标题（从评论对象中提取）
const getTargetTitle = (comment) => {
  // 如果评论对象中已有目标标题，直接使用
  if (comment.targetTitle) {
    return comment.targetTitle;
  }
  
  // 根据不同的目标类型，返回不同的默认标题
  if (comment.targetType === 3) {
    return '海洋生态保护课程';
  } else if (comment.targetType === 2) {
    return '海洋塑料污染报道';
  } else if (comment.targetType === 1) {
    return '海洋保护活动';
  }
  
  // 如果内容较长，截取一部分作为标题
  if (comment.content && comment.content.length > 15) {
    return comment.content.substring(0, 15) + '...';
  }
  
  return '未知内容';
}

// 处理标签切换
const handleTabChange = () => {
  currentPage.value = 1;
  fetchComments();
}

// 获取评论数据
const fetchComments = async () => {
  loading.value.stats = true
  loading.value.list = true
  
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 根据活动类型过滤
    if (activeTab.value !== 'all') {
      // 将前端标签转换为后端targetType
      if (activeTab.value === 'activity') {
        params.targetType = 1;
      } else if (activeTab.value === 'article') {
        params.targetType = 2;
      } else if (activeTab.value === 'course') {
        params.targetType = 3;
      }
    }
    
    const res = await getVolunteerComments(params)
    console.log('获取评论数据响应:', res);
    
    if (res.code === 200) {
      // 处理不同的后端数据结构
      if (res.data && Array.isArray(res.data)) {
        // 如果后端直接返回评论数组
        handleCommentsList(res.data);
        total.value = res.data.length; // 默认使用数组长度作为总数
      } else if (res.data && res.data.list) {
        // 如果后端返回带分页信息的数据结构
        handleCommentsList(res.data.list);
        total.value = res.data.total || res.data.list.length;
      } else {
        // 无数据情况
        rawComments.value = [];
        total.value = 0;
      }
    } else {
      ElMessage.error(res.message || '获取评论数据失败');
      rawComments.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取评论数据失败', error);
    ElMessage.error('获取评论数据失败');
    rawComments.value = [];
    total.value = 0;
  } finally {
    loading.value.stats = false;
    loading.value.list = false;
  }
}

// 处理评论列表数据
const handleCommentsList = (commentsData) => {
  if (!Array.isArray(commentsData)) {
    rawComments.value = [];
    return;
  }
  
  // 区分主评论和回复评论
  const mainComments = commentsData.filter(c => !c.parentId);
  const replyComments = commentsData.filter(c => c.parentId);
  
  // 设置主评论
  rawComments.value = mainComments;
  
  // 为每个主评论添加回复数量
  rawComments.value.forEach(mainComment => {
    // 找到该主评论的所有回复
    const replies = replyComments.filter(r => r.parentId === mainComment.id);
    mainComment.replyCount = replies.length;
  });
  
  // 统计评论数据
  stats.value = {
    commentCount: commentsData.length || 0,
    likeCount: commentsData.reduce((sum, comment) => sum + (comment.likeCount || 0), 0),
    featuredCount: commentsData.filter(c => c.likeCount && c.likeCount > 5).length
  };
}

// 获取回复详情
const loadReplies = async (comment) => {
  if (!comment.showReplies) {
    // 如果是关闭回复，直接返回
    return;
  }
  
  if (comment.replyList && comment.replyList.length > 0) {
    // 已经加载过，不需要再次加载
    return;
  }
  
  comment.loadingReplies = true;
  
  try {
    // 构建查询参数 - 根据parentId查询回复
    const params = {
      parentId: comment.id
    }
    
    const res = await getVolunteerComments(params)
    console.log('获取回复数据响应:', res);
    
    if (res.code === 200) {
      // 处理不同的后端数据结构
      let replyList = [];
      
      if (Array.isArray(res.data)) {
        replyList = res.data;
      } else if (res.data && res.data.list) {
        replyList = res.data.list;
      }
      
      // 转换回复数据
      comment.replyList = replyList.map(reply => {
        return {
          id: reply.id,
          username: reply.userName || reply.username || '未知用户',
          content: reply.content,
          time: new Date(reply.createTime || reply.time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        };
      });
    } else {
      ElMessage.warning(res.message || '无法加载回复');
      comment.replyList = [];
    }
  } catch (error) {
    console.error('获取回复失败', error);
    ElMessage.error('获取回复失败');
    // 保持空数组
    comment.replyList = [];
  } finally {
    comment.loadingReplies = false;
  }
}

// 切换回复显示状态
const toggleReplies = async (comment) => {
  comment.showReplies = !comment.showReplies;
  if (comment.showReplies) {
    await loadReplies(comment);
  }
}

// 删除评论
const handleDelete = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteComment(comment.id);
    
    if (res.code === 200) {
      ElMessage.success(res.message || '评论已删除');
      // 从列表中移除评论
      const index = rawComments.value.findIndex(c => c.id === comment.id);
      if (index !== -1) {
        rawComments.value.splice(index, 1);
        // 更新评论统计
        stats.value.commentCount = Math.max(0, stats.value.commentCount - 1);
      } else {
        // 如果直接移除失败，刷新整个评论列表
        fetchComments();
      }
    } else {
      ElMessage.error(res.message || '删除评论失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败', error);
      ElMessage.error('删除评论失败');
    }
  }
}

// 点赞/取消点赞
const handleLike = async (comment) => {
  try {
    const res = await toggleLike(comment.id);
    
    if (res.code === 200) {
      // 更新UI状态
      comment.liked = !comment.liked;
      comment.likes += comment.liked ? 1 : -1;
      
      // 更新点赞统计
      stats.value.likeCount += comment.liked ? 1 : -1;
      
      ElMessage.success(comment.liked ? '点赞成功' : '已取消点赞');
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('点赞操作失败', error);
    ElMessage.error('操作失败');
  }
}

// 查看详情
const viewDetail = (comment) => {
  try {
    // 定义评论对象映射关系
    const contentTypeMapping = {
      'activity': '活动',
      'article': '文章',
      'course': '课程'
    };

    // 获取内容类型名称
    const contentTypeName = contentTypeMapping[comment.type] || '内容';
    
    // 定义对应的路由路径
    const routePaths = {
      'activity': '/activities',
      'article': '/news',
      'course': '/education'
    };
    
    // 获取对应的路由路径
    const basePath = routePaths[comment.type];
    
    if (basePath) {
      // 构建完整路径
      const path = `${basePath}/${comment.targetId}`;
      
      // 检查路由是否存在
      const routeExists = router.hasRoute(path) || 
                         router.getRoutes().some(route => 
                           route.path === path || 
                           route.path === `${basePath}/:id`
                         );
      
      if (routeExists) {
        // 使用router导航
        router.push(path);
        return;
      }
    }
    
    // 如果路由不存在，显示提示信息
    ElMessage({
      type: 'info',
      message: `您正在查看${contentTypeName} ID: ${comment.targetId}，该详情页面目前不可用`,
      duration: 3000
    });
    
    // 打印更多详情供调试
    console.log('评论详情:', {
      type: comment.type,
      targetType: comment.targetType,
      targetId: comment.targetId,
      content: comment.content,
      routePath: basePath ? `${basePath}/${comment.targetId}` : '未知路径'
    });
  } catch (error) {
    console.error('查看详情失败', error);
    ElMessage.error('查看详情失败，该内容可能不存在或路由未配置');
  }
}

// 监听分页变化
watch(currentPage, () => {
  fetchComments()
})

// 页面加载时获取数据
onMounted(() => {
  fetchComments()
})
</script>

<style scoped lang="scss">
.volunteer-comments {
  .stats-card {
    margin-bottom: 20px;

    .stat-item {
      text-align: center;
      padding: 20px;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #409EFF;
        margin-bottom: 8px;
      }

      .stat-label {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .comments-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .comments-list {
      .comment-item {
        padding: 20px;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        .comment-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .target-info {
            display: flex;
            align-items: center;
            gap: 10px;

            .target-title {
              color: #606266;
            }
          }

          .comment-time {
            color: #909399;
            font-size: 13px;
          }
        }

        .comment-author {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .author-name {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }
        }

        .comment-content {
          color: #303133;
          line-height: 1.6;
          margin-bottom: 12px;
          padding-left: 30px;
        }

        .comment-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .interactions {
            display: flex;
            gap: 16px;

            .interaction-item {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #909399;
              font-size: 13px;
              cursor: pointer;
              transition: all 0.3s ease;

              &:hover {
                color: #409EFF;
              }

              &.active {
                color: #E6A23C;
              }

              .el-icon {
                font-size: 16px;
              }
            }
          }
        }

        .replies-list {
          margin-top: 12px;
          padding: 12px;
          background: #f5f7fa;
          border-radius: 4px;

          .reply-item {
            padding: 8px 0;
            
            &:not(:last-child) {
              border-bottom: 1px solid #ebeef5;
            }

            .reply-content {
              margin-bottom: 4px;

              .replier {
                color: #409EFF;
                font-weight: 500;
              }
            }

            .reply-time {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }

    .pagination {
      margin-top: 20px;
      text-align: center;
    }
  }
}
</style> 